package com.bjpowernode.listener;

import com.bjpowernode.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 应用关闭监听器。实现ApplicationListener接口，这个接口是spring框架的应用监听器接口，
 * 泛型是事件类型，下面的这个ContextClosedEvent事件是spring容器关闭事件
 */
@Component
public class ApplicationShutdownListener
        implements ApplicationListener<ContextClosedEvent> {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 事件触发后调用的函数,结合泛型，就是spring容器上下文关闭时调用的函数
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        System.out.println("Spring Context 关闭了......");
        //项目关闭后，要让所有登录用户的token失效，也就是把redis中的token删除
        redisTemplate.delete(Constant.REDIS_TOKEN_KEY);
    }
}
